package com.chinairi.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinairi.common.utils.IdGenerator;
import com.chinairi.common.utils.UserSession;
import com.chinairi.mall.controller.viewobject.GoodsInfoVO;
import com.chinairi.mall.controller.viewobject.ProjectPlanPurchaseQualityVO;
import com.chinairi.mall.controller.viewobject.ProjectPlanPurchaseServiceVO;
import com.chinairi.mall.controller.viewobject.ProjectPlanPurchaseVO;
import com.chinairi.mall.dao.*;
import com.chinairi.mall.error.BusinessException;
import com.chinairi.mall.error.EmBusinessError;
import com.chinairi.mall.model.*;
import com.chinairi.mall.service.IProjectPlanPurchaseService;
import com.chinairi.mall.service.modelobject.CompShopMO;
import com.chinairi.mall.util.NumberFormatUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gsl
 * @since 2020-09-19
 */
@Service
public class ProjectPlanPurchaseServiceImpl extends ServiceImpl<ProjectPlanPurchaseMapper, ProjectPlanPurchase> implements IProjectPlanPurchaseService {

    @Autowired
    private ProjectPlanPurchaseMapper projectPlanPurchaseMapper;

    @Autowired
    private ProjectPlanReqDetailMapper projectPlanReqDetailMapper;

    @Autowired
    private ProjectPlanPurchaseTransportMapper projectPlanPurchaseTransportMapper;

    @Autowired
    private ProjectPlanPurchaseStorageMapper projectPlanPurchaseStorageMapper;

    @Autowired
    private ProjectPlanPurchaseQualityMapper projectPlanPurchaseQualityMapper;

    @Autowired
    private ProjectPlanPurchaseSettleMapper projectPlanPurchaseSettleMapper;

    @Autowired
    private ProjectPlanPurchaseBuyMapper projectPlanPurchaseBuyMapper;

    @Autowired
    private ProjectPlanPurchaseControlMapper projectPlanPurchaseControlMapper;
    @Autowired
    private ProjectServiceImpl projectService;
    @Autowired
    private ContractMaitainMapper contractMaitainMapper;

    /**
     * 根据规则生成流水号
     * @param numberDigit 流水号的位数
     * @param numberValue 流水号的值
     * @return 流水号的值的字符串信息
     */
    private String numberFormat(int numberDigit, int numberValue) {
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumIntegerDigits(numberDigit);
        formatter.setGroupingUsed(false);
        return formatter.format(numberValue);
    }
    /**
     * 生成需求计划
     *
     * @param projectPlanPurchaseVO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ProjectPlanPurchaseVO projectPlanPurchaseVO) {
        //六位流水号
        String planReqId = NumberFormatUtil.numberFormat(4,projectPlanPurchaseMapper.getPlanPurchaseNo());
        projectPlanPurchaseVO.setPlanPurchaseId(planReqId);
        projectPlanPurchaseVO.setCreateUserName(UserSession.getUserName());
        projectPlanPurchaseVO.setCreateUser(UserSession.getUserId());
        projectPlanPurchaseVO.setCreateTime(new Date());
        projectPlanPurchaseVO.setUpdateUser(UserSession.getUserId());
        projectPlanPurchaseVO.setUpdateTime(new Date());
        //插入采购计划主表
        projectPlanPurchaseMapper.insert(projectPlanPurchaseVO);
        List<ProjectPlanReqDetail> projectPlanReqDetailList = projectPlanPurchaseVO.getProjectPlanReqDetailList();
        List<String> planDetailIdList = new ArrayList<>();
        if (projectPlanReqDetailList.size() > 0) {
            for (ProjectPlanReqDetail projectPlanReqDetail : projectPlanReqDetailList) {
                planDetailIdList.add(projectPlanReqDetail.getPlanDetailId());
            }
            List<ProjectPlanReqDetail> projectPlanReqDetailListResult = projectPlanReqDetailMapper.getListForPurchaseAdd(planDetailIdList);
            //绑定需求计划下的物料和采购计划编号，此时不应是批量更新是批量插入
            if (projectPlanReqDetailListResult.size() > 0) {
                projectPlanReqDetailMapper.batchInsert(projectPlanReqDetailListResult.stream().map((list) -> {
                    list.setPlanDetailId(UUID.randomUUID().toString().replace("-", ""));
                    list.setPlanPurchaseId(planReqId);
                    list.setPlanReqNumNow(list.getPlanReqNum());
                    list.setCreateUser(UserSession.getUserId());
                    list.setCreateTime(new Date());
                    return list;
                }).collect(Collectors.toList()));
            }
        }
        projectService.putRedis();
    }

    /**
     * 获取某个需求计划下的采购计划列表
     *
     * @param planReqId
     */
    @Override
    public List<ProjectPlanPurchase> getList(String planReqId) {
        QueryWrapper<ProjectPlanPurchase> wrapper = new QueryWrapper<>();
        wrapper.eq("PLAN_REQ_ID", planReqId);
        List<ProjectPlanPurchase> projectPlanPurchaseList = projectPlanPurchaseMapper.selectList(wrapper);
        if (projectPlanPurchaseList == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "暂无采购计划");
        }
        return projectPlanPurchaseList;
    }

    /**
     * 获取采购计划详情
     *
     * @param planPurchaseId
     * @return
     */
    @Override
    public List<ProjectPlanReqDetail> getReqDetail(String planPurchaseId) {
        if (planPurchaseId == null || "".equals(planPurchaseId)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "采购计划参数为空");
        }
        List<ProjectPlanReqDetail> details = projectPlanReqDetailMapper.getList("", planPurchaseId);
        if (!CollectionUtils.isEmpty(details)) {
            //遍历查看物料是否为需求计划中的产品
            for (ProjectPlanReqDetail detail : details) {
                Float shoppingCarNum = projectPlanReqDetailMapper.getShoppingCarNum(detail.getPlanPurchaseId(), detail.getPlanMatCode());
                detail.setPlanAddShoppingCarNum(shoppingCarNum == null ? 0.0F : shoppingCarNum);
                detail.setFrame(projectPlanReqDetailMapper.isExistMat(detail.getPlanReqId(), detail.getPlanMatCode()) > 0);
            }
        }
        return details;
    }
    /**
     * 获取供应商排行榜
     *
     * @param planPurchaseId
     * @return
     */
    @Override
    public Map<String, List<CompShopMO>> getShopRankList(String planPurchaseId) {
        List<CompShopMO> compShopMOList = projectPlanPurchaseMapper.getShopRankList(planPurchaseId);
        if (compShopMOList == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "没有获取到店铺");
        }
        Map<String, List<CompShopMO>> map = new HashMap<>(16);
        for (CompShopMO compShopMO : compShopMOList) {
            if (map.containsKey(compShopMO.getCsDbid())) {
                map.get(compShopMO.getCsDbid()).add(compShopMO);
            } else {
                List<CompShopMO> compShopMOS = new ArrayList<>();
                compShopMOS.add(compShopMO);
                map.put(compShopMO.getCsDbid(), compShopMOS);
            }
        }
        return map;
    }

    /**
     * 按店铺集中采购商品
     *
     * @return
     */
    @Override
    public List<GoodsInfoVO> getCollectByShop(List<String> goodsDbidList) {
        List<GoodsInfoVO> goodsInfoVOList = projectPlanPurchaseMapper.getCollectByShop(goodsDbidList);
        if (goodsInfoVOList == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "没有符合条件的商品");
        }
        return goodsInfoVOList;
    }

    /**
     * 采购计划添加服务
     *
     * @param stringObjectMap
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addService(HashMap<String, Object> stringObjectMap) {
        //采购服务标志
        String purchase = "qwe02";
        //质控服务标志
        String quality = "qwe03";
        //配送服务标志
        String transport = "qwe04";
        //仓储服务标志
        String storage = "qwe05";
        //结算服务标志
        String settle = "qwe06";
        ObjectMapper objectMapper = new ObjectMapper();
        stringObjectMap.forEach((key, value) -> {
            if (key.equals(purchase)) {
                ProjectPlanPurchaseBuy projectPlanPurchaseBuy = objectMapper.convertValue(value, ProjectPlanPurchaseBuy.class);
                projectPlanPurchaseBuy.setBuyId(IdGenerator.UUID());
                projectPlanPurchaseBuy.setCreateUser(UserSession.getUserId());
                projectPlanPurchaseBuy.setCreateTime(new Date());
                projectPlanPurchaseBuy.setServiceTypeName("采购服务");
                projectPlanPurchaseBuyMapper.insert(projectPlanPurchaseBuy);
            }
            //添加配送服务
            if (key.equals(transport)) {
                ProjectPlanPurchaseTransport projectPlanPurchaseTransport = objectMapper.convertValue(value, ProjectPlanPurchaseTransport.class);
                projectPlanPurchaseTransport.setTransportId(IdGenerator.UUID());
                projectPlanPurchaseTransport.setCreateUser(UserSession.getUserId());
                projectPlanPurchaseTransport.setCreateTime(new Date());
                projectPlanPurchaseTransport.setServiceTypeName("配送服务");
                projectPlanPurchaseTransportMapper.insert(projectPlanPurchaseTransport);
            }
            //添加仓储服务
            if (key.equals(storage)) {
                ProjectPlanPurchaseStorage projectPlanPurchaseStorage = objectMapper.convertValue(value, ProjectPlanPurchaseStorage.class);
                projectPlanPurchaseStorage.setStorageId(IdGenerator.UUID());
                projectPlanPurchaseStorage.setCreateUser(UserSession.getUserId());
                projectPlanPurchaseStorage.setCreateTime(new Date());
                projectPlanPurchaseStorage.setServiceTypeName("仓储服务");
                projectPlanPurchaseStorageMapper.insert(projectPlanPurchaseStorage);
            }
            //质控服务
            if (key.equals(quality)) {
                ProjectPlanPurchaseQualityVO projectPlanPurchaseQualityVO = objectMapper.convertValue(value, ProjectPlanPurchaseQualityVO.class);
                projectPlanPurchaseQualityVO.setQualityId(IdGenerator.UUID());
                projectPlanPurchaseQualityVO.setCreateUser(UserSession.getUserId());
                projectPlanPurchaseQualityVO.setCreateTime(new Date());
                projectPlanPurchaseQualityVO.setServiceTypeName("质控服务");
                projectPlanPurchaseQualityMapper.insert(projectPlanPurchaseQualityVO);
            }
            //结算服务
            if (key.equals(settle)) {
                ProjectPlanPurchaseSettle projectPlanPurchaseSettle = objectMapper.convertValue(value, ProjectPlanPurchaseSettle.class);
                projectPlanPurchaseSettle.setSettleId(IdGenerator.UUID());
                projectPlanPurchaseSettle.setCreateUser(UserSession.getUserId());
                projectPlanPurchaseSettle.setCreateTime(new Date());
                projectPlanPurchaseSettle.setServiceTypeName("结算服务");
                projectPlanPurchaseSettleMapper.insert(projectPlanPurchaseSettle);
            }
        });
    }

    /**
     * 获取采购计划中绑定的服务
     *
     * @param planPurchaseId
     * @return
     */
    @Override
    public ProjectPlanPurchaseServiceVO getService(String planPurchaseId) {
        ProjectPlanPurchaseServiceVO projectPlanPurchaseServiceVO = new ProjectPlanPurchaseServiceVO();
        //配送服务
        QueryWrapper<ProjectPlanPurchaseTransport> transportQueryWrapper = new QueryWrapper<>();
        transportQueryWrapper.eq("PLAN_PURCHASE_ID", planPurchaseId);
        ProjectPlanPurchaseTransport projectPlanPurchaseTransport = projectPlanPurchaseTransportMapper.selectOne(transportQueryWrapper);
        projectPlanPurchaseServiceVO.setProjectPlanPurchaseTransport(projectPlanPurchaseTransport);
        //仓储服务
        QueryWrapper<ProjectPlanPurchaseStorage> storageQueryWrapper = new QueryWrapper<>();
        storageQueryWrapper.eq("PLAN_PURCHASE_ID", planPurchaseId);
        ProjectPlanPurchaseStorage projectPlanPurchaseStorage = projectPlanPurchaseStorageMapper.selectOne(storageQueryWrapper);
        projectPlanPurchaseServiceVO.setProjectPlanPurchaseStorage(projectPlanPurchaseStorage);
        //质控服务
        QueryWrapper<ProjectPlanPurchaseQuality> qualityQueryWrapper = new QueryWrapper<>();
        qualityQueryWrapper.eq("PLAN_PURCHASE_ID", planPurchaseId);
        ProjectPlanPurchaseQuality projectPlanPurchaseQuality = projectPlanPurchaseQualityMapper.selectOne(qualityQueryWrapper);
        projectPlanPurchaseServiceVO.setProjectPlanPurchaseQuality(projectPlanPurchaseQuality);
        //结算服务
        QueryWrapper<ProjectPlanPurchaseSettle> settleQueryWrapper = new QueryWrapper<>();
        settleQueryWrapper.eq("PLAN_PURCHASE_ID", planPurchaseId);
        ProjectPlanPurchaseSettle projectPlanPurchaseSettle = projectPlanPurchaseSettleMapper.selectOne(settleQueryWrapper);
        projectPlanPurchaseServiceVO.setProjectPlanPurchaseSettle(projectPlanPurchaseSettle);
        //生产过程控制
        QueryWrapper<ProjectPlanPurchaseControl> controlQueryWrapper = new QueryWrapper<>();
        controlQueryWrapper.eq("PLAN_PURCHASE_ID", planPurchaseId);
        ProjectPlanPurchaseControl projectPlanPurchaseControl = projectPlanPurchaseControlMapper.selectOne(controlQueryWrapper);
        projectPlanPurchaseServiceVO.setProjectPlanPurchaseControl(projectPlanPurchaseControl);
        return projectPlanPurchaseServiceVO;
    }

    /**
     * 更新采购计划中的额服务
     *
     * @param purchaseService
     */
    @Override
    public void addOrUpdateService(ProjectPlanPurchaseServiceVO purchaseService) {
        Date date = new Date();
        String userId = UserSession.getUserId();
        ProjectPlanPurchaseTransport transport = purchaseService.getProjectPlanPurchaseTransport();
        if (transport != null) {
            if (transport.getTransportId() == null || "".equals(transport.getTransportId())) {
                transport.setTransportId(IdGenerator.UUID());
                transport.setCreateUser(userId);
                transport.setCreateTime(new Date());
                transport.setServiceTypeName("配送服务");
                projectPlanPurchaseTransportMapper.insert(transport);
            } else {
                transport.setUpdateUser(userId);
                transport.setUpdateTime(date);
                projectPlanPurchaseTransportMapper.updateById(transport);
            }
        }
        ProjectPlanPurchaseStorage storage = purchaseService.getProjectPlanPurchaseStorage();
        if (storage != null) {
            if (storage.getStorageId() == null || "".equals(storage.getStorageId())) {
                storage.setStorageId(IdGenerator.UUID());
                storage.setCreateUser(UserSession.getUserId());
                storage.setCreateTime(new Date());
                storage.setServiceTypeName("仓储服务");
                projectPlanPurchaseStorageMapper.insert(storage);
            } else {
                storage.setUpdateUser(userId);
                storage.setUpdateTime(date);
                projectPlanPurchaseStorageMapper.updateById(storage);
            }
        }
        ProjectPlanPurchaseQuality quality = purchaseService.getProjectPlanPurchaseQuality();
        if (quality != null) {
            if (quality.getQualityId() == null || "".equals(quality.getQualityId())) {
                quality.setQualityId(IdGenerator.UUID());
                quality.setCreateUser(UserSession.getUserId());
                quality.setCreateTime(new Date());
                quality.setServiceTypeName("质控服务");
                projectPlanPurchaseQualityMapper.insert(quality);
            } else {
                quality.setUpdateUser(userId);
                quality.setUpdateTime(date);
                projectPlanPurchaseQualityMapper.updateById(quality);
            }
        }
        ProjectPlanPurchaseSettle settle = purchaseService.getProjectPlanPurchaseSettle();
        if (settle != null) {
            if (settle.getSettleId() == null || "".equals(settle.getSettleId())) {
                settle.setSettleId(IdGenerator.UUID());
                settle.setCreateUser(UserSession.getUserId());
                settle.setCreateTime(new Date());
                settle.setServiceTypeName("结算服务");
                projectPlanPurchaseSettleMapper.insert(settle);
            } else {
                settle.setUpdateUser(userId);
                settle.setUpdateTime(date);
                projectPlanPurchaseSettleMapper.updateById(settle);
            }
        }
        ProjectPlanPurchaseControl control  = purchaseService.getProjectPlanPurchaseControl();
        if (control != null) {
            if (control.getControlId() == null || "".equals(control.getControlId())) {
                control.setControlId(IdGenerator.UUID());
                control.setCreateUser(UserSession.getUserId());
                control.setCreateTime(new Date());
                projectPlanPurchaseControlMapper.insert(control);
            } else {
                control.setUpdateUser(userId);
                control.setUpdateTime(date);
                projectPlanPurchaseControlMapper.updateById(control);
            }
        }
    }

    /**
     * 获取用户自己所有的采购计划列表
     *
     * @return
     */
    @Override
    public List<ProjectPlanPurchaseVO> getAllList() {
        Integer uciCompCharacter = contractMaitainMapper.selectUciCompCharacter(UserSession.getUserId());
        //查询当前用户的子级用户id
        List<String> childUserIdList=projectPlanPurchaseMapper.getChildUserIds(UserSession.getUserId());
        return projectPlanPurchaseMapper.selectByUserId(UserSession.getUserId(),uciCompCharacter,childUserIdList);
    }


    /**
     * 根据服务类型查询服务商
     *
     * @param serviceType
     * @return
     */
    @Override
    public List<UserCompanyInfo> getServerCompByType(String serviceType) {
        return projectPlanPurchaseMapper.selectServerCompByType(serviceType);
    }


}
